package com.example.demo.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.example.demo.Enums.LimitType;
import com.example.demo.annotation.RateLimiter;
import com.example.demo.dao.UserMapper;
import com.example.demo.strategy.context.StrategyTestContext;
import com.example.demo.support.multipart.MultipartData;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Author: LJP
 * @Description:
 * @Date: Created in 14:34 2022/1/22
 */
@RestController
@RequestMapping("/test")
@SuppressWarnings("rawtypes")
public class TestController {

    private final StrategyTestContext strategyTestContext;
    private final RedisTemplate redisTemplate;
    private final UserMapper userMapper;

    public TestController(StrategyTestContext strategyTestContext, RedisTemplate redisTemplate, UserMapper userMapper) {
        this.strategyTestContext = strategyTestContext;
        this.redisTemplate = redisTemplate;
        this.userMapper = userMapper;
    }

    @GetMapping("/strategy")
    @RateLimiter(time = 3, count = 1, limitType = LimitType.IP)
    public void strategyTest() {
        strategyTestContext.setStrategyTestMap();
    }

    @PostMapping("/import")
    public List<List<Object>> importExcel(MultipartFile file) throws IOException {

        InputStream stream = new ByteArrayInputStream(file.getBytes());

        ExcelReader reader = ExcelUtil.getReader(stream);

        return reader.read();
    }

    @GetMapping("/redis")
    @SuppressWarnings("unchecked")
    public Object setValueToRedis(String key, String value) {
        ValueOperations ops = redisTemplate.opsForValue();
        ops.set(key, value);
        return ops.get("ljp");
    }

    @GetMapping("/time")
    @RateLimiter(time = 3, count = 1)
    public String getProjectStartTime() {
        long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
        Date date = new Date(startTime);
        return DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
    }

    @GetMapping
    public List<MultipartData> test() {
        return userMapper.getUserInfo();
    }
}
